package com.example.zzx.dovebook.bookshare.upload

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.MenuItem
import android.widget.ImageView
import androidx.lifecycle.Observer
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.example.baselibrary.commonutil.Logger
import com.example.baselibrary.commonutil.ToastUtil
import com.example.baselibrary.constant.Constant
import com.example.baselibrary.image.GlideManager
import com.example.baselibrary.image.PhotoPicker
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.CommonRepository
import com.example.zzx.dovebook.base.CommonViewModel
import com.example.zzx.dovebook.base.ValueWrapper.TYPE_FAILED
import com.example.zzx.dovebook.base.ValueWrapper.TYPE_NORMAL
import com.example.zzx.dovebook.base.extensions.startLocationActivityForResult
import com.example.zzx.dovebook.base.extensions.startUserDetailActivity
import com.example.zzx.dovebook.login.LoginCheck
import com.example.zzx.dovebook.user.UserManager
import com.example.zzx.dovebook.utils.FileController
import com.example.zzx.dovebook.utils.LocationUtil
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_FAIL
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_LOADING
import kotlinx.android.synthetic.main.activity_book_share_upload.*
import java.io.File

class BookShareUploadActivity: BaseActivity<CommonViewModel<CommonRepository>>() {

    private lateinit var bookNet: BookNet

    private var currentLatLon: LatLonPoint? = null
    private var currentLocationInfo: String? = null

    private var descriptionInfo: String = ""

    private lateinit var photoPicker: PhotoPicker

    private lateinit var tipDialog: QMUITipDialog

    override fun getLayoutId(): Int = R.layout.activity_book_share_upload

    override fun createViewModel(): Class<CommonViewModel<CommonRepository>> = CommonViewModel::class.java as Class<CommonViewModel<CommonRepository>>

    override fun createRepository(): Any = CommonRepository()

    override fun initIntent(savedInstanceState: Bundle?) {
        bookNet = intent.getParcelableExtra(getString(R.string.book_net_arg_name))
    }

    override fun initViews(savedInstanceState: Bundle?) {
        setupToolbar()

        photoPicker = PhotoPicker().apply {
            compress = true
            fileProviderAuthorities = FileController.COVER_FILE_PROVIDER_AUTHORITIES
            tempPhotoPath = FileController.getTempCoverPath(this@BookShareUploadActivity)
        }

        tipDialog = QMUITipDialog.Builder(this)
            .setIconType(ICON_TYPE_LOADING)
            .setTipWord("上传中")
            .create(true)

        bindDisplayViews()
    }

    override fun initOptions(savedInstanceState: Bundle?) {

        getLocationInfo()
    }

    private fun getLocationInfo() {
        LocationUtil.locationAndGeocode(this, object : GeocodeSearch.OnGeocodeSearchListener {
            override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, resultCode: Int) {
                if (resultCode != 1000) {
                    Logger.e(TAG, "onRegeocodeSearched -> 获取地址信息失败!")
                    return
                }
                val address = regeocodeResult.regeocodeAddress
                if (address.pois.size == 0) {
                    val latitude = UserManager.getInstance(this@BookShareUploadActivity).latitude
                    val longitude = UserManager.getInstance(this@BookShareUploadActivity).longitude
                    currentLatLon = LatLonPoint(latitude, longitude)
                } else {
                    val poiItem = address.pois[0]
                    currentLatLon = poiItem.latLonPoint
                    currentLocationInfo = address.city + address.district + poiItem.title
                    locationTv.text = currentLocationInfo
                }
            }

            override fun onGeocodeSearched(geocodeResult: GeocodeResult, i: Int) {

            }
        }, true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SEARCH_LOCATION && resultCode == RESULT_OK) {
            data?.apply {
                val poiItem: PoiItem = getParcelableExtra(getString(R.string.result_location_arg_name))
                currentLatLon = poiItem.latLonPoint
                currentLocationInfo = poiItem.cityName + poiItem.adName + poiItem.title
                locationTv.text = currentLocationInfo
            }
        }
    }

    private fun bindDisplayViews() {
        locationTv.setOnClickListener {
            startLocationActivityForResult(currentLatLon, currentLocationInfo, REQUEST_CODE_SEARCH_LOCATION)
        }
        bookNet.apply {
            if (!TextUtils.isEmpty(PhotoUrl)) {
                downloadBookPhoto(PhotoUrl)
            }
            if (!TextUtils.isEmpty(Author)) {
                authorTv.text = Author
            }
        }
        bookImg.setOnClickListener {
            photoPicker.setOnPickListener {
                bookNet.PhotoUrl = it
                this@BookShareUploadActivity.bookImg.scaleType = ImageView.ScaleType.CENTER_CROP
                GlideManager.loadImage(this@BookShareUploadActivity, bookNet.PhotoUrl,
                    this@BookShareUploadActivity.bookImg)
            }
        }
        descriptionEdit.addTextChangedListener(object: TextWatcher {
            override fun afterTextChanged(s: Editable) {
                if (!TextUtils.isEmpty(s.toString())) {
                    descriptionInfo = s.toString()
                    uploadTv.isEnabled = true
                } else {
                    descriptionInfo = ""
                    uploadTv.isEnabled = false
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
        uploadTv.setOnClickListener {
            uploadBookShare()
        }
    }

    private fun downloadBookPhoto(photoUrl: String?) {
        GlideManager.downloadImage(this@BookShareUploadActivity, photoUrl, object: RequestListener<File> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<File>?,
                isFirstResource: Boolean
            ): Boolean = false

            override fun onResourceReady(
                resource: File,
                model: Any?,
                target: Target<File>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                bookNet.PhotoUrl = FileController.saveBookCover(this@BookShareUploadActivity, resource)
                if (!TextUtils.isEmpty(bookNet.PhotoUrl)) {
                    bookImg.scaleType = ImageView.ScaleType.CENTER_CROP
                    GlideManager.loadImage(this@BookShareUploadActivity, bookNet.PhotoUrl, bookImg)
                }
                return false
            }

        })

    }

    @LoginCheck
    private fun uploadBookShare() {
        if (TextUtils.isEmpty(bookNet.PhotoUrl) || bookNet.PhotoUrl!!.startsWith(Constant.BASE_URL_BOOK_PHOTO)) {
            ToastUtil.shortToast(this, "请先选择一张图片")
            return
        }
        tipDialog.show()
        if (currentLatLon == null) {
            currentLatLon = LatLonPoint(0.00000000, 0.0000000)
        }
        viewModel.uploadBookShare(bookNet.BookName, bookNet.Author, bookNet.ISBN,
            UserManager.getInstance(this).loginUserId, descriptionInfo, currentLatLon!!.latitude,
            currentLatLon!!.longitude, bookNet.PhotoUrl!!).observe(this, Observer {
            tipDialog.dismiss()
            if (it.type == TYPE_NORMAL) {
                startUserDetailActivity(UserManager.getInstance(this@BookShareUploadActivity).loginUserId,
                    UserManager.getInstance(this@BookShareUploadActivity).loginUserName)
//                tipDialog = QMUITipDialog.Builder(this@BookShareUploadActivity)
//                    .setIconType(ICON_TYPE_SUCCESS)
//                    .setTipWord("上传成功")
//                    .create()
//                tipDialog.show()
                finish()
                return@Observer
            } else if (it.type == TYPE_FAILED) {
                tipDialog = QMUITipDialog.Builder(this@BookShareUploadActivity)
                    .setIconType(ICON_TYPE_FAIL)
                    .setTipWord("上传失败")
                    .create()
                tipDialog.show()
            }
            mainHandler.postDelayed({
                if (tipDialog.isShowing) {
                    tipDialog.dismiss()
                }
            }, 1500)
        })
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    companion object {
        private const val REQUEST_CODE_SEARCH_LOCATION = 0x01
    }

}